package com.admin.service

import com.admin.dao.IndexCaseAdminDao
import com.data.annotation.NoargAnnotation
import com.data.annotation.OpenAnnotation
import com.data.bean.IndexCase
import com.data.entity.IndexCaseEntity
import com.data.util.CheckDataUtils
import com.data.util.DatabaseIdUtils
import com.data.util.FinalStringUtils
import com.data.util.ImageLookUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.web.multipart.commons.CommonsMultipartFile

import java.util.Date

/**
 * FileName: IndexCaseAdminService
 * Author:   HingLo
 * Date:     2017/11/6 10:05
 * Description: 案例管理的服务层
 */
@Service
@OpenAnnotation
@NoargAnnotation
class IndexCaseAdminService {
    @Autowired
    var indexCaseAdminDao: IndexCaseAdminDao? = null

    fun listIndexCaseService(): List<IndexCase> = this.indexCaseAdminDao!!.listIndexCaseDao()

    fun showImageService(image: String): ByteArray? =
            ImageLookUtils.readImage(FinalStringUtils.INDEXCASEIMAGEPAHT, image)

    fun deleteIndexCaseService(id: String): Boolean {
        if (CheckDataUtils.stringUtilsID(id)) {
            val indexCase = indexCaseAdminDao!!.findByIdIndexCaseDao(id)
            val imageName = indexCase?.image//获取文件的名称
            val path = FinalStringUtils.INDEXCASEIMAGEPAHT + imageName

            val bool = this.indexCaseAdminDao!!.deleteIndexCaseDao(id) > 0 //删除数据库中的数据
            if (bool) ImageLookUtils.deleteImage(path)//数据库中的数据删除成功后就直接删除本地文件
            return bool //返回结果值
        }
        return false
    }

    fun changeStateService(id: String, state: Boolean): Boolean {
        return if (CheckDataUtils.stringUtilsID(id)) {
            val indexCaseEntity = IndexCaseEntity(id = id, state = state)
            indexCaseAdminDao!!.changeStateDao(indexCaseEntity) > 0
        } else false
    }

    fun submitIndexCaseService(image: CommonsMultipartFile, indexCase: IndexCase): Boolean {
        val isuffix = ImageLookUtils.getFileSuffix(image)
        if (CheckDataUtils.iconUtils(isuffix!!)) {
            val fileName = DatabaseIdUtils.dataIdOne + isuffix
            if (ImageLookUtils.saveFile(FinalStringUtils.INDEXCASEIMAGEPAHT + fileName, image)) { //保存背景图
                indexCase.id = DatabaseIdUtils.dataIdOne
                indexCase.date = Date()
                indexCase.image = fileName
                indexCase.state = false
                //保存到数据库中
                return this.indexCaseAdminDao!!.saveMassageDao(indexCase) > 0
            }


        }


        return false

    }
}
